/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.validation;

import com.codemagi.servlets.AppException;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

/**
 * Validate that an input is a valid Boolean ie: It is a valid Boolean object or is a String either "true" or "false"
 */
public class BooleanValidator implements IValidator {

    Logger log = Logger.getLogger(this.getClass());

    protected static String MSG_INVALID_BOOLEAN = "Invalid boolean entered. Please check your data and try again.";

    /** Optionally check that the boolean is a specific value */
    private Boolean value = null;

    /** Optional message to return when input does not match the expected value */
    private String mismatchMessage = "Boolean entered does not match expected value.";

    public BooleanValidator() {
	//nada
    }

    public BooleanValidator(Boolean value) {
	this.value = value;
    }

    public BooleanValidator(Boolean value, String mismatchMessage) {
	this.value = value;
	this.mismatchMessage = mismatchMessage;
    }

    public Object validate(Object obj, HttpServletRequest request) throws AppException {

	log.debug("Validating obj: " + obj);

	//sanity check
	if (obj == null) {
	    Boolean output = new Boolean(false);
	    if (value != null && !value.equals(output)) throw new AppException(mismatchMessage);
	    return output;
	}

	if (obj instanceof Boolean) {	    
	    if (value != null && !value.equals(obj)) throw new AppException(mismatchMessage);
	    return obj;
	}

	if (obj instanceof String) {
	    Boolean output = Boolean.valueOf( (String)obj );
	    if (value != null && !value.equals(output)) throw new AppException(mismatchMessage);
	    return output;
	}

	return obj;
    }

}
